from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import List, Optional

mcp = FastMCP("Startdde MCP Server")

"""
面向软件：startdde（deepin 桌面环境启动器）

MCP tools 列表：
1. startdde_version
   - 用途：获取 startdde 版本信息
   - 参数：无
   - 返回结构：统一 JSON 格式

2. startdde_no_xsession_scripts
   - 用途：启动 startdde 但不执行 Xsession 脚本
   - 参数：无
   - 返回结构：统一 JSON 格式
"""

@mcp.tool()
def startdde_version() -> dict:
    """
    获取 startdde 版本信息
    
    返回：
        JSON 结构：
        {
            "success": bool,      # 命令是否成功执行
            "command": str,       # 执行的完整命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出内容
            "stderr": str         # 标准错误内容
        }
    """
    cmd = ["startdde", "--version"]
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out after 30 seconds"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Command execution failed: {str(e)}"
        }

@mcp.tool()
def startdde_no_xsession_scripts() -> dict:
    """
    启动 startdde 但不执行 Xsession 脚本
    
    这个参数用于在启动 deepin 桌面环境时跳过 Xsession 脚本的执行。
    
    返回：
        JSON 结构：
        {
            "success": bool,      # 命令是否成功执行
            "command": str,       # 执行的完整命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出内容
            "stderr": str         # 标准错误内容
        }
    """
    cmd = ["startdde", "-no-xsession-scripts"]
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out after 30 seconds"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Command execution failed: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()